<template lang="pug">
.view.cp-con-data-supply.fix-flex-pos
  el-row(:gutter="20", style="height: 100%")
    //- 左边一级type
    el-col.left-radio-wrap.vertical-radio(:span="3")
      el-radio-group(v-model="firstType", size="medium", @change="changeFirst", :class="{'single': allFirstType.length == 1}")
        el-radio-button(
            v-for="(item, index) in allFirstType",
            :key="index",
            :label="item.value") {{item.name}}
    //- 左边二级type
    el-col.mid-radio-wrap.vertical-radio(:span="3")
      el-radio-group(v-model="secondType", @change="changeSecond", :class="{'single': allSecondType.length == 1}")
        el-radio-button(
            v-for="(item, index) in allSecondType",
            :key="index",
            :label="item.value") {{item.name}}
    //- 中间内容
    el-col.mid-content-wrap(:span="17")
      .material-table(v-show="secondType !== custom")
        .table-wrap
          el-table(
            :data="maTableList",
            highlight-current-row,
            v-loading="loadingTable",
            size="mini",
            height="100%",
            border)
            el-table-column(show-overflow-tooltip, align="center", label="名称")
              template(slot-scope="scope")
                div(v-show="!scope.row.canEdit") {{scope.row.name}}
                div(v-show="scope.row.canEdit")
                  el-input(v-model="scope.row.name")
            el-table-column(show-overflow-tooltip, align="center", label="编码")
              template(slot-scope="scope")
                div(v-show="!scope.row.canEdit") {{scope.row.value}}
                div(v-show="scope.row.canEdit")
                  el-input(v-model="scope.row.value")
            el-table-column(show-overflow-tooltip, align="center", label="状态")
              template(slot-scope="scope")
                div(v-show="!scope.row.canEdit") {{statusText(scope.row.status)}}
                div(v-show="scope.row.canEdit")
                  el-radio(v-model="scope.row.status", label="0") 启用
                  el-radio(v-model="scope.row.status", label="1") 禁用
            el-table-column(show-overflow-tooltip, align="center", label="操作", min-width="100px", v-if="isEdit")
              template(slot-scope="scope")
                div(v-show="!scope.row.canEdit", :class="{enable: true}")
                  i.icon-act.el-icon-edit(@click="editItem(scope.$index, scope.row)")
                  i.icon-act.el-icon-plus(@click="addItem(scope.$index, scope.row)")
                  i.icon-act.el-icon-arrow-up(@click="moveUpItem(scope.$index, scope.row)")
                  i.icon-act.el-icon-arrow-down(@click="moveDownItem(scope.$index, scope.row)")
                  i.icon-act.el-icon-delete(@click="deleteItem(scope.$index, scope.row)")
                div(v-show="scope.row.canEdit", class="enable")
                  i.icon-act.el-icon-check(@click="saveEditItem(scope.$index, scope.row)")
                  i.icon-act.el-icon-close(@click="cancelEditItem(scope.$index, scope.row)")
        .init-btn
          el-button(
            v-show="(!maTableList || !maTableList.length) && isEdit",
            type="primary", @click="initList") 初始化行
          el-button(type="primary", icon="el-icon-edit", v-show="!isEdit", @click="editTable") 编辑
          el-button(v-show="isEdit", @click="cancelEdit") 取消
          el-button(type="primary", v-show="isEdit", @click="saveTable") 保存
      .custom-table(v-show="secondType === custom")
        CustomTypeTable
</template>

<script>
import ConfigApi from '@/api/config';
import CustomTypeTable from './customTypeTable';

// 自定义分类
const CUSTOM = { name: '自定义分类', value: 'custom' };
// 物料类别value
const SKU = 'sku';

export default {
  name: 'condatasupply',
  components: {
    CustomTypeTable
  },
  data() {
    return {
      custom: CUSTOM.value,
      isEdit: false,
      firstType: 0,
      secondType: 0,
      allFirstType: [],
      allSecondType: [],
      loadingTable: false,
      maTableList: []
    };
  },
  created() {
    // 缓存编辑数据
    this.dataCache = [];
    this.editCache = [];
  },
  mounted() {
    this.loadDataType();
  },
  methods: {
    // 状态文本
    statusText(val) {
      if (val === '0') {
        return '启用';
      } else if (val === '1') {
        return '禁用';
      } else {
        return null;
      }
    },
    // 获取类别数据
    loadDataType() {
      ConfigApi.getDataType().then((res) => {
        if (res && res.length) {
          res.forEach((item) => {
            // 物料类别下添加自定义分类
            if (item.value === SKU) {
              item.children.push(CUSTOM);
            }
          });
          this.allFirstType = res;
          this.firstType = res[0].value;
          this.allSecondType = res[0].children;
          this.secondType = this.allSecondType[0].value;
          this.loadDataDetail();
        }
      });
    },
    // 一级改变
    changeFirst(val) {
      const second = this.allFirstType.find(item => item.value === val);
      this.allSecondType = second.children;
      this.secondType = this.allSecondType[0].value;
      this.loadDataDetail();
    },
    // 二级改变
    changeSecond(val) {
      this.secondType = val;
      this.loadDataDetail();
    },
    // 获取详情
    loadDataDetail() {
      const secondType = this.secondType;
      if (secondType === this.custom) {
        return false;
      }
      this.loadingTable = true;
      ConfigApi.getDataDetail({ secondType }).then((res) => {
        this.maTableList = res;
        this.loadingTable = false;
      }).catch((error) => {
        this.loadingTable = false;
        console.log(JSON.stringify(error));
      });
    },
    // 编辑表格
    editTable() {
      this.dataCache = [...this.maTableList];
      this.editCache = [...this.maTableList];
      this.isEdit = true;
    },
    // 校验表格
    volidTable() {
      let canSave = true;
      if (this.maTableList && this.maTableList.length) {
        this.maTableList.forEach((item, index) => {
          const arr = [];
          if (!item.name) {
            arr.push('名称');
          }
          if (!item.value) {
            arr.push('编码');
          }
          if (!item.status && item.status !== 0) {
            arr.push('状态');
          }
          if (arr.length) {
            this.$message.error(`第${index + 1}行${arr.join('、')}不能为空`);
            canSave = false;
            return false;
          }
          if (item.canEdit) {
            this.$message.error(`请先确认第${index + 1}行`);
            canSave = false;
            return false;
          }
        });
      }
      return canSave;
    },
    // 保存表格
    saveTable() {
      if (!this.volidTable()) {
        return false;
      }
      const group = this.allFirstType.find(item => item.value === this.firstType);
      const property = this.allSecondType.find(item => item.value === this.secondType);
      const params = {
        groupName: group.name,
        propertyName: property.name,
        groupValue: this.firstType,
        propertyValue: this.secondType,
        children: this.maTableList
      };
      ConfigApi.saveDataDetail(params).then((res) => {
        if (res.status === 0) {
          this.$message({ message: '保存成功', type: 'success' });
          this.isEdit = false;
        } else {
          this.$message.error(res.comment || '保存失败');
        }
      }).catch((error) => {
        this.$message.error('网络不给力，请稍后再试');
        console.log(JSON.stringify(error));
      });
    },
    // 取消编辑
    cancelEdit() {
      this.maTableList = this.editCache;
      this.dataCache = this.editCache;
      this.isEdit = false;
    },
    /* ****** 表格操作  ****** */
    // 初始化
    initList() {
      this.maTableList.push({ status: '0', canEdit: true });
      this.dataCache.push({ status: '0', canEdit: true, fromAdd: true });
    },
    // 编辑
    editItem(index) {
      this.dataCache[index] = Object.assign({}, this.maTableList[index]);
      this.$set(this.maTableList[index], 'canEdit', true);
    },
    // 新增
    addItem(index) {
      this.maTableList.splice((index + 1), 0, { status: '0', canEdit: true });
      this.dataCache.splice((index + 1), 0, { status: '0', canEdit: true, fromAdd: true });
    },
    // 上移
    moveUpItem(index) {
      // 上一行
      const prev = index - 1;
      const newData = [...this.maTableList];
      if (newData[prev]) {
        // 取得前一行的数据
        const target = newData.splice(prev, 1)[0];
        // 放在需要上移行的后面，当前行索引在index-1
        newData.splice(index, 0, target);
        this.maTableList = newData;
      } else {
        this.$message({
          message: '亲，不能再上移了~',
          type: 'warning'
        });
      }
    },
    // 下移
    moveDownItem(index) {
      // 下一行
      const next = index + 1;
      const newData = [...this.maTableList];
      if (newData[next]) {
        // 取得下一行的数据
        const target = newData.splice(next, 1)[0];
        // 放在需要上移行的后面，当前行索引在index-1
        newData.splice(index, 0, target);
        this.maTableList = newData;
      } else {
        this.$message({
          message: '亲，不能再下移了~',
          type: 'warning'
        });
      }
    },
    // 删除
    deleteItem(index) {
      // if (this.maTableList.length < 2) return;
      this.maTableList.splice(index, 1);
      this.dataCache.splice(index, 1);
    },
    // 保存
    saveEditItem(index) {
      this.maTableList[index].canEdit = false;
    },
    // 取消
    cancelEditItem(index) {
      const cache = Object.assign({}, this.dataCache[index], { canEdit: false });
      if (cache.fromAdd) {
        // 新增时取消
        this.maTableList.splice(index, 1);
        this.dataCache.splice(index, 1);
      } else {
        // 编辑时取消
        this.maTableList.splice(index, 1, cache);
        this.maTableList[index].canEdit = false;
      }
    }
  }
};
</script>

<style lang="sass">
@import "../../../styles/utils"
.cp-con-data-supply
  overflow-x: hidden
  overflow-y: auto
  background $THMECOLOR
  padding-top: 20px
  padding-left: 20px
  padding-bottom: 20px
  height: 100%
  .el-row, .el-col
    height: 100%
  .el-radio-button
    display: block
  .left-radio-wrap, .mid-radio-wrap
    .el-radio-button__inner
      width: 100px
  .vertical-radio
    .el-radio-button .el-radio-button__inner
      border-left: 1px solid #dcdfe6
      border-bottom-width: 0
    .el-radio-button__orig-radio:checked+.el-radio-button__inner
      border-color: #409EFF
    .el-radio-button:first-child .el-radio-button__inner
      border-radius: 4px 4px 0 0
    .el-radio-button:last-child .el-radio-button__inner
      border-radius: 0 0 4px 4px
      border-bottom-width: 1px
    .single
      .el-radio-button:first-child .el-radio-button__inner,
      .el-radio-button:last-child .el-radio-button__inner
        border-radius: 4px 4px 4px 4px
  .mid-content-wrap, .material-table
    height: 100%
  .table-wrap
    height: calc(100% - 50px)
    background: red
  .init-btn
    height: 50px
    line-height: 50px
    text-align: center
  .custom-table
    height: 100%
    overflow: auto
  .icon-act
    font-size: 16px
    font-weight: 500
    cursor: pointer
    margin-left: 3px
    margin-right: 3px
    &:hover
      color: #5D9BFB
</style>
